package com.xinjian.jianba.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.GsonBuilder;
import com.xinjian.jianba.dto.DetailedUserInfoDto;
import com.xinjian.jianba.dto.ForgetPasswordDto;
import com.xinjian.jianba.dto.IndexDto;
import com.xinjian.jianba.dto.LoginDto;
import com.xinjian.jianba.dto.LoginVo;
import com.xinjian.jianba.dto.PasswordUpdateDto;
import com.xinjian.jianba.dto.RegisterUserDto;
import com.xinjian.jianba.dto.UserInfoDto;
import com.xinjian.jianba.dto.UserInfoVo;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.service.UserService;
import com.xinjian.jianba.service.ValidatorService;
import com.xinjian.jianba.utils.JsonUtil;
import com.xinjian.jianba.utils.LogBuilder;
import com.xinjian.jianba.utils.ModuleEnum;

@RestController
@RequestMapping("/api/v3/jianba/user")
public class UserController extends AbstractController {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private ValidatorService validatorService;

	@PostMapping(value = { "/register" })
	public String register(@RequestBody RegisterUserDto registerUserDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户注册,参数 registerUserDto={}"), JsonUtil.getJsonString(registerUserDto));
		if (registerUserDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}

		try {
			validatorService.valid(registerUserDto);
			
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, userService.register(registerUserDto));
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	/**
	 * 用户登录.
	 */
	@PostMapping(value = { "/login" })
	public String login(@RequestBody LoginDto loginDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户登录,参数 LoginUserDto={}"), JsonUtil.getJsonString(loginDto));
		if (loginDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}
		try {
			validatorService.valid(loginDto);
			LoginVo vo = userService.login(loginDto);
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, vo);
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	/**
	 * 用户退出登录
	 * 
	 */
	@PostMapping(value = { "/logout" })
	public String logout(@RequestBody UserInfoDto userInfoDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户退出登录,参数 userInfoDto={}"), JsonUtil.getJsonString(userInfoDto));
		if (userInfoDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}
		try {
			validatorService.valid(userInfoDto);
			userService.logout(userInfoDto);
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	/**
	 * 忘记密码
	 */
	@PostMapping(value = { "/forgetPassword" })
	public String forgetPassword(@RequestBody ForgetPasswordDto forgetPasswordDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户忘记密码,参数 forgetPasswordDto={}"), JsonUtil.getJsonString(forgetPasswordDto));
		if (forgetPasswordDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}

		try {
			validatorService.valid(forgetPasswordDto);
			if (!(forgetPasswordDto.getPassword().trim().equals(forgetPasswordDto.getRePassword().trim()))) {
				return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "两次输入密码不一致!");
			}
			userService.forgetPassword(forgetPasswordDto);
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	@PostMapping(value = { "/setPassword" })
	public String setPassword(@RequestBody ForgetPasswordDto forgetPasswordDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户忘记密码,参数 forgetPasswordDto={}"), JsonUtil.getJsonString(forgetPasswordDto));
		if (forgetPasswordDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}

		try {
			validatorService.valid(forgetPasswordDto);
			if (!(forgetPasswordDto.getPassword().trim().equals(forgetPasswordDto.getRePassword().trim()))) {
				return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "两次输入密码不一致!");
			}
			userService.forgetPassword(forgetPasswordDto);
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	/**
	 * 修改密码
	 */
	@PostMapping(value = { "/passwordUpdate" })
	public String passwordUpdate(@RequestBody PasswordUpdateDto passwordUpdateDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户忘记密码,参数 passwordUpdateDto={}"), JsonUtil.getJsonString(passwordUpdateDto));

		if (passwordUpdateDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}
		try {
			validatorService.valid(passwordUpdateDto);
			if (!(passwordUpdateDto.getPassword().trim().equals(passwordUpdateDto.getRePassword().trim()))) {
				return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "两次输入密码不一致!");
			}
			userService.passwordUpdate(passwordUpdateDto);
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	/**
	 * 用户资料
	 */
	@PostMapping(value = { "/userInfo" })
	public String userInfo(@RequestBody UserInfoDto userInfoDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户信息,参数 userInfoDto={}"), JsonUtil.getJsonString(userInfoDto));

		if (userInfoDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}
		try {
			validatorService.valid(userInfoDto);
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, userService.userInfo(userInfoDto));
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	/**
	 * 注册后用户资料编辑
	 */
	@PostMapping(value = { "/updateUserInfo" })
	public String updateUserInfo(@RequestBody UserInfoVo userInfoVo) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "注册后用户资料编辑,参数 userInfoVo={}"), JsonUtil.getJsonString(userInfoVo));

		if (userInfoVo == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}
		try {
			userService.updateUserInfo(userInfoVo);
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	/**
	 * 注册时完善资料
	 */
	@PostMapping(value = { "/consummationData" })
	public String consummationData(@RequestBody DetailedUserInfoDto detailedUserInfoDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户完善信息,参数 detailedUserInfoDto={}"), JsonUtil.getJsonString(detailedUserInfoDto));
		try {
			validatorService.valid(detailedUserInfoDto);
			Map<String, Object> map = userService.consummationData(detailedUserInfoDto);
			Map<String, Object> rt = new HashMap<String, Object>();
			rt.put("code", ResponseCode.SUCCESS + "");
			rt.put("message", ResponseCode.SUCCESS_MSG);
			rt.put("result", map);
			//防止RongYunToken的字符串里有"=="或其它特殊字符转换后乱码的情况
			String resultStr = new GsonBuilder().disableHtmlEscaping().create().toJson(rt);
			LOGGER.info("-----resultStr--------" + resultStr);
			return resultStr;
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}

	}

	/**
	 * 用户首页信息.
	 */
	@PostMapping(value = { "/index" })
	public String index(@RequestBody IndexDto indexDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.User, "用户首页信息,参数 indexDto={}"), JsonUtil.getJsonString(indexDto));
		if (indexDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}
		try {
			validatorService.valid(indexDto);
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, userService.selectIndexInfoById(indexDto));
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
	}

	/**
	 * 用户tab信息.
	 */
	@PostMapping(value = { "/indexTab" })
	public String indexTab() {
		try {
			List<Map<String, String>> places = new ArrayList<Map<String, String>>();
			//			0：擦肩；1：同行；2:共度；3：身边
						Map<String, String> meetTimeMap = new HashMap<String, String>();
						meetTimeMap.put("typeName", "擦肩");
						meetTimeMap.put("typeNameId", "0");
						places.add(meetTimeMap);
						Map<String, String> meetDistanceMap = new HashMap<String, String>();
						meetDistanceMap.put("typeName", "同行");
						meetDistanceMap.put("typeNameId", "1");
						places.add(meetDistanceMap);
//						Map<String, String> meetDurationMap = new HashMap<String, String>();
//						meetDurationMap.put("typeName", "共度");
//						meetDurationMap.put("typeNameId", "2");
//						places.add(meetDurationMap);
			Map<String, String> nearByMap = new HashMap<String, String>();
			nearByMap.put("typeName", "身边");
			nearByMap.put("typeNameId", "3");
			places.add(nearByMap);

			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, places);
		} catch (Exception e) {
			LOGGER.error("--------error--->>>>>", e);
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
		}
		@PostMapping(value="/sex/choose")
		public String sexChoose(@RequestBody Map<String,String> map){
			String userId=map.get("userId");
			String sexChoose=map.get("sexChoose");
			if(userId==null||userId.equals("")||sexChoose==null||sexChoose.equals("")){
				return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "用户id和选择性别不能为空");
			}
			int result=userService.sexChoose(Long.parseLong(userId), Integer.parseInt(sexChoose));
			if(result>0){
				return this.responseClientJsonData(ResponseCode.SUCCESS, "设置成功");
			}else{
				return this.responseClientJsonData(ResponseCode.ERROR, "更新失败");
			}
		}
		@PostMapping(value="/info/id")
		public String acquire(@RequestBody Map<String,String> map){
			String userId=map.get("userId");
			if(userId==null||userId.equals("")){
				return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "用户id不能为空");
			}
			LoginVo vo=null;
			if(userId.indexOf("a")>0){
				userId=userId.substring(0, userId.length()-1);
				vo=	userService.getInfoByUserId(userId);
			}else if(userId.indexOf("b")>0){
				userId=userId.substring(0, userId.length()-1);
				vo=	userService.getBuziInfoByUserId(userId);
			}
			
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, vo);
		}
	}
